# ===============================
# Stage 1: Build frontend (Vue3 + Vite)
# ===============================
FROM node:20 AS frontend-builder
WORKDIR /frontend
COPY frontend/ .
RUN yarn install && yarn build

# ===============================
# Stage 2: Build Go backend (with OCR libs)
# ===============================
FROM golang:1.22-bullseye AS backend-builder

# Use Aliyun mirrors for faster package downloads
RUN sed -i 's|http://deb.debian.org/debian|https://mirrors.aliyun.com/debian|g' /etc/apt/sources.list

RUN apt-get update && apt-get install -y \
    build-essential cmake pkg-config \
    libjpeg-dev libpng-dev libtiff-dev \
    libavcodec-dev libavformat-dev libswscale-dev \
    libxvidcore-dev libx264-dev libgtk-3-dev \
    libtesseract-dev libleptonica-dev tesseract-ocr \
    tesseract-ocr-chi-sim tesseract-ocr-eng \
    libopencv-dev python3-opencv \
    git && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY backend/ .
COPY --from=frontend-builder /frontend/dist ./frontend-dist

RUN go mod download && go build -o server main.go

# ===============================
# Stage 3: Final runtime image
# ===============================
FROM debian:bullseye-slim

RUN apt-get update && apt-get install -y \
    libtesseract-dev libleptonica-dev \
    libjpeg62-turbo libpng16-16 libtiff5 \
    libgtk-3-0 libavformat58 libswscale5 \
    tesseract-ocr tesseract-ocr-chi-sim tesseract-ocr-eng && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=backend-builder /app/server .
COPY --from=backend-builder /app/frontend-dist ./frontend-dist

EXPOSE 8080
CMD ["./server"]
